<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="addFn">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template #default="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRows.name" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <template #default="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.editRows.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state === 1 ? '已启用' : '未启用' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template #default="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRows.description" type="textarea" size="mini" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="300">
          <template #default="{ row }">
            <template v-if="row.isEdit">
              <el-button type="primary" size="mini" @click="editBtnFn(row)">确定</el-button>
              <el-button size="mini" @click="cancel(row)">取消</el-button>
            </template>
            <template v-else>
              <el-button type="text" size="mini" @click="getPermissionListTree(row.id)">分配权限</el-button>
              <el-button type="text" size="mini" style="margin-right: 10px;" @click="editFn(row)">编辑</el-button>
              <el-popconfirm
                title="确定删除这一项吗？"
                @onConfirm="delFn(row.id)"
              >
                <el-button slot="reference" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          layout="prev, pager, next"
          :total="pagetotal"
          :page-size="pagesize"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <!-- 放置弹层 -->
      <el-dialog :title="title" :visible.sync="dialogVisible" width="30%">
        <el-form ref="form" :model="form" :rules="formRules" label-width="80px">
          <el-form-item prop="name" label="角色名称">
            <el-input v-model="form.name" placeholder="请输入内容" size="mini" />
          </el-form-item>
          <el-form-item label="启用">
            <el-switch v-model="form.state" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" @click="addsubmit">确认</el-button>
            <el-button size="mini" @click="handleClose">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 气泡弹出层 -->
      <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
        <el-tree ref="dialogTree" :data="permissionData" node-key="id" :default-checked-keys="permIds" show-checkbox default-expand-all :props="{label:'name'}" />
        <el-button type="primary" size="mini" @click="btnOk">确认</el-button>
        <el-button size="mini" @click="btnCancel">取消</el-button>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permission'
import { addRole, assignPerm, delRole, getRoleDetail, getRoleList, updateRole } from '@/api/role'
import { translateDataToTree } from '@/utils'

export default {
  name: 'Role',
  data() {
    return {
      list: null,
      page: 1,
      pagesize: 5,
      pagetotal: 0,
      dialogVisible: false,
      title: '',
      id: '',
      form: {
        id: '',
        name: '',
        state: '',
        description: ''
      },
      formRules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      showPermissionDialog: false,
      permissionData: [],
      permIds: []
    }
  },
  created() {
    this.getData()
  },
  methods: {
    btnCancel() {
      this.showPermissionDialog = false
    },
    // 获取权限列表数据,转化为树形结构
    async getPermissionListTree(id) {
      this.permIds = []
      this.form.id = id
      this.permissionData = translateDataToTree(await getPermissionList(), 0)
      // 获取角色具体权限
      const res = await getRoleDetail(id)
      this.permIds = res.permIds
      this.showPermissionDialog = true
    },
    // 确认权限数据修改
    async btnOk() {
      console.log(this.form.id)
      console.log(this.$refs.dialogTree.getCheckedKeys())
      const res = await assignPerm({ id: this.form.id, permIds: this.$refs.dialogTree.getCheckedKeys() })
      console.log(res)
      this.$message.success('分配权限成功')
      this.showPermissionDialog = false
    },
    async getData() {
      const res = await getRoleList({ page: this.page, pagesize: this.pagesize })
      this.list = res.rows
      this.pagetotal = res.total
      res.rows.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRows', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    handleCurrentChange(val) {
      this.page = val
      this.getData()
    },
    // 关闭弹层
    handleClose(done) {
      this.dialogVisible = false
      this.$refs.form.resetFields()
    },
    // 点击添加按钮
    addFn() {
      this.dialogVisible = true
      this.title = '新增角色'
    },
    // 点击编辑按钮
    async editFn(data) {
      data.isEdit = true
      data.editRows.name = data.name
      data.editRows.state = data.state
      data.editRows.description = data.description
    },
    // 编辑确定
    async editBtnFn(row) {
      if (row.editRows.name === '' || row.editRows.description === '') {
        this.$message.error('请填写完整')
        return
      }
      row.name = row.editRows.name
      row.state = row.editRows.state
      row.description = row.editRows.description
      console.log(row)
      await updateRole({ ...row, id: row.id })
      this.$message.success('修改成功')
      // eslint-disable-next-line require-atomic-updates
      row.isEdit = false
    },
    // 取消编辑
    cancel(row) {
      row.isEdit = false
    },
    // 确认,发送添加请求
    async addsubmit() {
      console.log(this.form)
      await this.$refs.form.validate()
      console.log('111')
      await addRole(this.form)
      this.$message.success('添加成功')
      this.handleClose()
      this.getData()
    },
    // 删除功能
    async delFn(id) {
      const res = await delRole(id)
      console.log(res)
      this.$message.success('删除成功')
      if (this.list.length === 1 && this.page > 1) {
        this.page--
      }
      this.getData()
    }

  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
